/*
 * @Author: xiaosihan 
 * @Date: 2024-05-27 02:46:54 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-05-29 16:04:05
 */

import { DoubleSide, Group, Plane, ShaderChunk, ShaderMaterial, Vector3 } from "three";
import PlaneWithHtml from "three-base/PlaneWithHtml";
import threeLoader from "three-base/threeLoader";
import reflextionAlphaMapPNG from "./reflextionAlphaMap.png";
import threeUtils from "three-base/threeUtils";
import { get } from "lodash";
import Transition from "three-base/Transition";
import reflextionAlphaMap2PNG from "./reflextionAlphaMap2.png";

// 带倒影的html标签
export default class HtmlLableReflextion extends Group {
    constructor(html: string) {
        super();
        this.lable.setHtml(html);
        this.lable2.setHtml(html);
    }

    name = "--"

    //裁剪面1
    clipPlane1 = new Plane(new Vector3(0, 1, 0), 0);
    //裁剪面2
    clipPlane2 = new Plane(new Vector3(0, -1, 0), 0);

    // 2个组件同时加载完成是 这个值等于2
    loaded = 0;

    //标签文字
    lable = (() => {
        const lable = new PlaneWithHtml(``);
        lable.rotateX(Math.PI / 2);
        lable.scale.multiplyScalar(0.005);
        lable.addEventListener("loaded", () => {
            this.loaded += 1;
            this.lable2.geometry = this.lable.geometry;
            this.lable2.scale.copy(this.lable.scale);
            this.lable2.material = this.lable.material.clone();
            this.lable2.material.clippingPlanes = [this.clipPlane2];
            this.lable2.material.alphaMap = threeLoader.getTexture(reflextionAlphaMap2PNG);
            this.lable2.material.alphaTest = 0.001;

        });
        lable.material.clippingPlanes = [this.clipPlane1];
        lable.renderOrder = -1;
        this.add(lable);
        return lable;
    })();

    //标签文字倒影
    lable2 = (() => {
        const lable = new PlaneWithHtml(``);
        lable.rotateX(Math.PI / -2);
        lable.renderOrder = -1;
        this.add(lable);
        return lable;
    })();

    // 初始动画
    async init() {
        while (this.loaded !== 2) {
            await new Promise(resolve => setTimeout(resolve, 50));
            await new Promise(resolve => requestAnimationFrame(resolve));
        }
        const size = threeUtils.getSize(this.lable).clone();
        await this.transition.reset({ y: size.y / -2 });
        await this.transition.set({ y: size.y / 2 });
    }

    transition = (() => {
        const transition = new Transition({ y: -9999 });
        transition.setBezier([0, 0, 1, 1]);
        transition.setDuration(1000);
        transition.onChange(({ y }) => {
            this.lable.position.set(0, y, 0);
            this.lable2.position.set(0, -y, 0);
        });
        return transition;
    })();


}